package Homework03;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Homework03Server
{
    public static void main(String[] args) throws Exception
    {
        //监听9999端口
        ServerSocket serverSocket = new ServerSocket(9999);
        //等待客户端连接
        Socket socket = serverSocket.accept();
        //读取客服端发送的名字
        InputStream inputStream = socket.getInputStream();
        byte[] b = new byte[1024];
        int len=0;
        String downLoadFileName = "";
        while ((len = inputStream.read(b))!=-1)
        {
            downLoadFileName += new String(b,0,len);
        }
        System.out.println("客户端希望下载文件名="+downLoadFileName);
        String resFileName = "";
        if(downLoadFileName.equals("高山流水"))
            resFileName = "D:\\Jave\\高山流水.mp3";
        else
            resFileName = "D:\\Jave\\1.mp3";
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(resFileName));
        byte[] data = new byte[1024];
        data = streamToByteArray(bufferedInputStream);
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
        bufferedOutputStream.write(data);
        socket.shutdownOutput();

        inputStream.close();
        bufferedInputStream.close();
        bufferedOutputStream.close();
        serverSocket.close();
        System.out.println("服务端退出");

    }
    public static byte[] streamToByteArray(InputStream is) throws  Exception
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = is.read(b)) != -1)
        {
            bos.write(b,0,len);
        }
        byte[] array = bos.toByteArray();
        bos.close();
        return  array;
    }
}
